package com.ckerchina.admin.ckadmin.service.sms.util;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ckerchina.admin.ckadmin.service.sms.dto.SmsReceiveReport;
import com.ckerchina.admin.ckadmin.service.sms.dto.SmsSendResult;
import com.ckerchina.admin.ckadmin.service.sms.dto.SmsStatusReport;
import com.ckerchina.admin.ckadmin.utils.XmlUtils;

/**
 * 梦网短信短信发送工具
 */
public class MengWangSmsUtil {

	private static Logger logger = LoggerFactory.getLogger(MengWangSmsUtil.class);

	public static SmsSendResult sendMessage(String mobiles, String content, String URL, String userName,
			String password) {
		if (StringUtils.isEmpty(mobiles)) {
			throw new IllegalArgumentException("手机号码为空");
		}
		int iMobiCount = StringUtils.countMatches(mobiles, ",") + 1;
		try {
			String result = Request.Post(URL + "/MongateCsSpSendSmsNew")
					.bodyForm(Form.form().add("userId", userName).add("password", password).add("pszMobis", mobiles)
							.add("pszMsg", content).add("iMobiCount", iMobiCount + "").add("pszSubPort", "*").build(),
					Charset.forName("UTF-8")).execute().returnContent().asString();
			logger.debug("梦网返回, mobileid: " + mobiles + ", result: " + result);
			String str = StringUtils.substringBetween(result, "<string xmlns=\"http://tempuri.org/\">", "</string>");
			if (str.length() > 10 && str.length() < 25) { // 返回的流水大于10位小于25位为提交成功
				return new SmsSendResult(mobiles, content, true, str);
			} else {
				return new SmsSendResult(mobiles, content, false, str);
			}
		} catch (Exception e) {
			logger.error("梦网科技短信发送异常", e);
			return new SmsSendResult(mobiles, content, false, e.getMessage());
		}
	}

	public static Integer queryBalance(String URL, String userName, String password) {
		try {
			String result = Request.Post(URL + "/MongateQueryBalance")
					.bodyForm(Form.form().add("userId", userName).add("password", password).build(),
							Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("梦网返回: " + result);
			return Integer
					.parseInt(StringUtils.substringBetween(result, "<int xmlns=\"http://tempuri.org/\">", "</int>"));
		} catch (Exception e) {
			logger.error("梦网科技短信查询余额异常", e);
			throw new RuntimeException("短信查询余额异常", e);
		}
	}

	public static List<SmsStatusReport> queryStatusReport(String URL, String userName, String password) {
		List<SmsStatusReport> reportList = new ArrayList<SmsStatusReport>();
		try {
			String result = Request.Post(URL + "/MongateCsGetStatusReportExEx")
					.bodyForm(Form.form().add("userId", userName).add("password", password).build(),
							Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("梦网返回: " + result);
			List<String> list = XmlUtils.getTextForElements(result, "string");
			for (String s : list) {
				String[] split = s.split("\\,");
				String date = split[0];
				String time = split[1];
				String flowNo = split[2];
				String status = split[4] + "," + split[5];
				Date receiveDate = DateUtils.parseDate(date + " " + time, "yyyy-MM-dd hh:mm:ss");
				SmsStatusReport report = new SmsStatusReport(receiveDate, flowNo, status);
				reportList.add(report);
			}
			return reportList;
		} catch (Exception e) {
			logger.error("梦网科技短信状态报告异常", e);
		}
		return reportList;
	}

	public static List<SmsReceiveReport> receiveMessage(String URL, String userName, String password) {
		List<SmsReceiveReport> reportList = new ArrayList<SmsReceiveReport>();
		try {
			String result = Request.Post(URL + "/MongateCsGetSmsExEx")
					.bodyForm(Form.form().add("userId", userName).add("password", password).build(),
							Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("梦网返回: " + result);
			List<String> list = XmlUtils.getTextForElements(result, "string");
			for (String s : list) {
				String[] split = s.split("\\,");
				String date = split[0];
				String time = split[1];
				String mobile = split[2];
				String content = split[5];
				Date t = DateUtils.parseDate(date + " " + time, "yyyy-MM-dd hh:mm:ss");
				SmsReceiveReport report = new SmsReceiveReport(t, mobile, content);
				reportList.add(report);
			}
		} catch (Exception e) {
			logger.error("梦网科技短信查询上行短信异常", e);
		}
		return reportList;
	}
}
